package com.situ.mvc.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.situ.mvc.entity.Course;
import com.situ.mvc.entity.PageBean;
import com.situ.mvc.service.ICourseService;
import com.situ.mvc.service.impl.CourseServiceImpl;

@Controller
@RequestMapping(value="/course")
public class CourseController {
	 private ICourseService courseService = new CourseServiceImpl(); 
	
	@RequestMapping(value="/pageList")
	public String pageList(Integer pageNo,Integer pageSize,Model model) {
		if (pageNo == null) {
			pageNo = 1;
		}
		if (pageSize == null) {
			pageSize = 3;
		}
		PageBean<Course> pageBean = courseService.getPagBean(pageNo, pageSize);
		System.out.println(pageBean);
		model.addAttribute("pageBean",pageBean);
		return "course/course_list";
	}
	
	@RequestMapping(value="/deleteById")
	@ResponseBody
	public Boolean deleteById(Integer id) {
		boolean result =  courseService.deleteById(id);
		System.out.println(result ? "成功" : "失败");
		return result;
	}
	
	@RequestMapping(value="getInsertPage")
	public String getInsertPage(Model model) {
		return "course/course_insert";
	}
	
	@RequestMapping(value="/insert")
	@ResponseBody
	public Boolean insert(String name,Integer credit,String classhour,Model model) {
		Course course = new Course(name, credit, classhour);
		boolean resule = courseService.insert(course);
		return resule;
	}
	
	@RequestMapping(value="/toUpdate")
	public String toUpdata(Integer id,Model model) {
		Course course =  courseService.findById(id);
		model.addAttribute("course",course);
		return "course/course_update";
	}
	
	//修改数据
	@RequestMapping(value="/update")
	@ResponseBody
	private Boolean update(Integer id,String name,Integer credit,String classhour) {
		Course course = new Course(id, name, credit, classhour);
		//service方法
		boolean result = courseService.update(course);
		System.out.println(result ? "成功" : "失败");
		//重定向
		return result;
	}

	@RequestMapping(value="/checkName" )
	private void checkName(HttpServletRequest request, HttpServletResponse response, String name) throws IOException {
		boolean isExist =  courseService.checkName(name);
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write("{\"isExist\": "+isExist+"}");
		
	}
	

	//全部删除
	@RequestMapping(value="/deleteAll")
	@ResponseBody
	private Boolean deleteAll(String[] selectIds) {
		boolean result = courseService.deleteAll(selectIds);
		System.out.println(result ? "成功" : "失败");
		return result;		
	}

}
